package grobit.tracker

import grobit.torrent.Sha1Data

import java.nio.ByteBuffer

class TrackerResponse {
    String failureReason
    String warningMessage
    BigInteger interval
    BigInteger minInterval
    String trackerId
    BigInteger complete
    BigInteger incomplete
    List peers

    static TrackerResponse createFromMap(Map data) {
        TrackerResponse response = new TrackerResponse()
        response.failureReason = data.get('failure reason')
        response.warningMessage = data.get('warning message')
        response.interval = data.get('interval')
        response.minInterval = data.get('min interval')
        response.trackerId = data.get('tracker id')
        response.complete = data.get('complete')
        response.incomplete = data.get('incomplete')

        response.peers = createPeers(data.get('peers'))

        return response
    }

    static List createPeers(List peers) {
        println 'Creating list peers'
    }

    static List createPeers(String peers) {
        List rv = []
        assert (peers.length() % 6) == 0
        while(peers.length()) {
            InetAddress address = InetAddress.getByAddress(peers.substring(0, 4).getBytes('ISO-8859-1'))
            ByteBuffer buf = ByteBuffer.wrap(peers.substring(4, 6).getBytes('ISO-8859-1'))
            InetSocketAddress socketAddress = new InetSocketAddress(address, (buf.get()&0xFF)<<8 | (buf.get()&0xFF))
            rv.add(new Peer(address: socketAddress))
            peers = peers.substring(6)
        }
        return rv
    }

    @Override
    public String toString() {
        return "TrackerResponse{" +
                "failureReason='" + failureReason + '\'' +
                ", warningMessage='" + warningMessage + '\'' +
                ", interval=" + interval +
                ", minInterval=" + minInterval +
                ", trackerId='" + trackerId + '\'' +
                ", complete=" + complete +
                ", incomplete=" + incomplete +
                ", peers=" + peers +
                '}';
    }
}

class Peer {
    String peerId
    InetSocketAddress address

    @Override
    public String toString() {
        return "Peer{" +
                "peerId='" + peerId + '\'' +
                ", address=" + address +
                '}';
    }
}